﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using System.Collections;

/// <summary>
/// Summary description for CommonSession
/// </summary>
public class CommonSession
{
    public bool bForce { get; set; }
    public string queryString { get; set; }
    public DataSet dsList { get; set; }
    public List<int> arrDeleted { get; set; }

	public CommonSession()
	{
	}

	public static void ReadAppConfigFromDb(HttpApplicationState storage)
	{
		try
		{
			System.Data.DataSet ds = Hipocrate.DB.DBConnection.GetData("SELECT Code, Value FROM Global");
			storage["dbGlobal"] = ds;
			if ((ds != null) && (ds.Tables.Count > 0))
				foreach(System.Data.DataRow r in ds.Tables[0].Rows)
					if (r["Code"].ToString().Equals("Spital_Name"))
						storage["HNAME"] = r["Value"].ToString();
		}
		catch (System.Data.SqlClient.SqlException) { }
		//independently run the two queries, just in case the connection was restored in the mean time...
		try
		{
			System.Data.DataSet ds = Hipocrate.DB.DBConnection.GetData("SELECT Code, Value FROM Sysconf WHERE Enabled = 1");
			storage["dbSysconf"] = ds;
		}
		catch (System.Data.SqlClient.SqlException) { }
	}

	public class StareDiagramaIndicatori
	{
		public string sPageTitle;
		public string sChartTitle;
		public string sProcName;
		private object startDate;
		public object StartDate
		{
			set
			{
				if (value is TextBox)
					startDate = GetDate(value as TextBox);
				else
					startDate = value;
			}
			get { return startDate; }
		}
		private object endDate;
		public object EndDate
		{
			set
			{
				if (value is TextBox)
					endDate = GetDate(value as TextBox);
				else
					endDate = value;
			}
			get { return endDate; }
		}
		public int nTableIndex;
		public int nItemsPerPage;
		public int nCurrentPage;
		public string rowFilter;
		public string sortExpression;
		public string sortDirection;
		public string[] columnNames;
		public string[] columnIds;
		public string sChartType;

		public static object GetDate(TextBox txtControl)
		{
			string value = txtControl.Text.Trim();
			if (value.Length == 0)
				return null;
			DateTime result;
			if (DateTime.TryParse(value, out result))
				return result.ToString("dd/MM/yyyy"); //the SQL stored proc expects format "103" >:P
			return null;
		}
	}

	public class StareRapoarteLaborator
	{
		public string tipRaport;
		public DateTime startDate, endDate;
		public string strAnalysis, strSection, strMedic, strMedicType;
		public bool bSpecifiedPayType;
		public string strPayType;
		public bool bShowSums, bProcessed, bShowFullInfo, bTehnice, bNumeCodCAS, bShowRepeatCounts, bUnpaidToo, bInactiveToo, bInternalName, bInternalCode;
		public string strInvestigatie, strRezultat;
		public string comparerOp1, comparedValue1, compareType, comparerOp2, comparedValue2;
		public string groupBySection, groupByTypes; //NB: isEmpty OR startsWith: "*", "(", or "'".
		public string strFormat;
		public string strListaCoduri;
	}

	//alternatively: HttpContext instead of SessionPageBase
	public static string SetStareDiagramaIndicatori(SessionPageBase page, string chartTitle, System.Web.UI.ITemplate title,
		string procName, TextBox txtStart, TextBox txtEnd,
		int tableIndex, int itemsPerPage, int currentPage, string filter, string sortBy, string sortDir,
		DataControlFieldCollection columns, string chartType)
	{
		StareDiagramaIndicatori parametrii = new StareDiagramaIndicatori();
		parametrii.sPageTitle = GetText(title);
		parametrii.sChartTitle = chartTitle;
		parametrii.sProcName = procName;
		parametrii.StartDate = txtStart;
		parametrii.EndDate = txtEnd;
		parametrii.nTableIndex = tableIndex;
		parametrii.nItemsPerPage = itemsPerPage;
		parametrii.nCurrentPage = currentPage;
		parametrii.rowFilter = filter;
		parametrii.sortExpression = sortBy;
		parametrii.sortDirection = sortDir;
		parametrii.sChartType = chartType;
		parametrii.columnNames = new string[columns.Count];
		parametrii.columnIds = new string[columns.Count];
		int i = 0;
		foreach(DataControlField dcf in columns)
		{
			parametrii.columnNames[i] = dcf.HeaderText;
			parametrii.columnIds[i] = (dcf as BoundField).DataField;
			++i;
		}
		string guid = System.Guid.NewGuid().ToString("N");
		page.Session[guid] = parametrii;
		return guid;
	}

	public static string SetStareRapoarteLaborator(SessionPageBase page, string tipRaport, DateTime startDate, DateTime endDate,
		string strAnalysis, string strSection, string strMedic, string strMedicType,
		bool bSpecifiedPayType, string strPayType,
		bool bShowSums, bool bProcessed, bool bShowFullInfo, bool bTehnice, bool bNumeCodCAS,
		bool bShowRepeatCounts, bool bUnpaidToo, bool bInactiveToo, bool bInternalName, bool bInternalCode,
		string strInvestigatie, string strRezultat,
		string comparerOp1, string comparedValue1, string compareType, string comparerOp2, string comparedValue2,
		string groupBySection, string groupByTypes, string strListaCoduri, string strFormat)
	{
		StareRapoarteLaborator parametrii = new StareRapoarteLaborator();
		parametrii.tipRaport = tipRaport;
		parametrii.startDate = startDate;
		parametrii.endDate = endDate;
		parametrii.strAnalysis = strAnalysis;
		parametrii.strSection = strSection;
		parametrii.strMedic = strMedic;
		parametrii.strMedicType = strMedicType;
		parametrii.bSpecifiedPayType = bSpecifiedPayType;
		parametrii.strPayType = strPayType;
		parametrii.bShowSums = bShowSums;
		parametrii.bProcessed = bProcessed;
		parametrii.bShowFullInfo = bShowFullInfo;
		parametrii.bTehnice = bTehnice;
		parametrii.bNumeCodCAS = bNumeCodCAS;
		parametrii.bShowRepeatCounts = bShowRepeatCounts;
		parametrii.bUnpaidToo = bUnpaidToo;
		parametrii.bInactiveToo = bInactiveToo;
		parametrii.bInternalName = bInternalName;
		parametrii.bInternalCode = bInternalCode;
		parametrii.strInvestigatie = strInvestigatie;
		parametrii.strRezultat = strRezultat;
		parametrii.comparerOp1 = comparerOp1;
		parametrii.comparedValue1 = comparedValue1;
		parametrii.compareType = compareType;
		parametrii.comparerOp2 = comparerOp2;
		parametrii.comparedValue2 = comparedValue2;
		parametrii.groupBySection = groupBySection;
		parametrii.groupByTypes = groupByTypes;
		parametrii.strFormat = strFormat;
		parametrii.strListaCoduri = strListaCoduri;
		string guid = System.Guid.NewGuid().ToString("N");
		page.Session[guid] = parametrii;
		return guid;
	}

	private static string GetText(System.Web.UI.ITemplate iTemplate)
	{
		Label dummy = new Label();
		iTemplate.InstantiateIn(dummy);
		string result = dummy.Text.Replace("<br/>", " ").Replace("<br />", " ");
		foreach(System.Web.UI.Control c in dummy.Controls)
			if(c is System.Web.UI.ITextControl)
				result += (c as System.Web.UI.ITextControl).Text.Replace("<br/>", " ").Replace("<br />", " ");
		return result;
	}

    public static StareRapoarteLaborator GetParameterStareRL(SessionPageBase page, string guid)
	{
        return page.Session[guid] as StareRapoarteLaborator;
	}

    public static System.Data.DataTable GetContents(SessionPageBase page, string guid, out StareDiagramaIndicatori parametrii)
    {
        parametrii = page.Session[guid] as StareDiagramaIndicatori;
        if (parametrii == null) return null;
        return Hipocrate.DB.DBConnection.GetData(parametrii.sProcName, new string[] { "StartDate", "EndDate" },
            new object[] { parametrii.StartDate, parametrii.EndDate }).Tables[parametrii.nTableIndex];
    }

    public static DataSet ToDataTable(IEnumerable<iCustomDAO.Customer> collection)
    {
        DataSet ds = new DataSet("dsList");
        DataTable dt = new DataTable("DataTable");
		Type t = typeof(iCustomDAO.Customer);
        PropertyInfo[] pia = t.GetProperties();

        foreach (PropertyInfo pi in pia)
        {
            Type ColumnType = pi.PropertyType;
            if ((ColumnType.IsGenericType))
            {
                ColumnType = ColumnType.GetGenericArguments()[0];
            }
            dt.Columns.Add(pi.Name, ColumnType);
        }

        foreach (iCustomDAO.Customer item in collection)
        {
            DataRow dr = dt.NewRow();
            dr.BeginEdit();
            foreach (PropertyInfo pi in pia)
            {
                if (pi.GetValue(item, null) != null)
                {
                    dr[pi.Name] = pi.GetValue(item, null);
                }
            }
            dr.EndEdit();
            dt.Rows.Add(dr);
        }

        ds.Tables.Add(dt);
        return ds;
    }
}
